package com.ruoyi.file.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.file.storage.FileStorage;
import com.ruoyi.file.storage.impl.LocalFileStorage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @description: [一句话描述该类的功能]
 * @author: [wangshujun]
 * @createDate: [2020/9/21 13:57]
 * @version: [v1.0]
 */

@RefreshScope
@RestController
@RequestMapping("/file")
public class FileStorageController extends BaseController {
    /**
     * 本地文件根目录
     */
    @Value("${local.path}")
    private String fileRootDir;

    /**
     * 上传文件服务
     * @param file 文件
     * @param path 自定义文件目录，为空直接上传到根目录
     * @return
     */
    @PostMapping("/upload")
    @Log(title = "文件上传" , businessType = BusinessType.INSERT)
    public R<String> upload(@RequestParam("file") MultipartFile file,@RequestParam("path")String path){
        String uploadPath = fileRootDir;
        if(StringUtils.isNotEmpty(path)){
            uploadPath+=path;
        }
        FileStorage fileStorage = new LocalFileStorage(uploadPath);
        Assert.notNull(fileStorage,"文件上传没有初始化");
        Assert.isTrue(fileStorage.getClass().equals(LocalFileStorage.class),"没有初始化上传接口");
        try {
            Assert.notNull(file,"文件不能为空");
            String  fileName = file.getOriginalFilename();

            String key =  UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
            fileStorage.store(file.getInputStream(),key);
            return R.ok(path+key);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传失败");
        }
    }

}
